#ifndef __TCP_SERVER_H__
#define __TCP_SERVER_H__


#include <memory>
#include <functional>
#include "iomanager.h"
#include "address.h"
#include "socket.h"
#include "noncopyable.h"

namespace sylar {

class TcpServer : public std::enable_shared_from_this<TcpServer> 
                    , Noncopyable{
public:
    typedef std::shared_ptr<TcpServer> ptr;
    TcpServer(sylar::IOManager* woker = sylar::IOManager::GetThis()
            ,sylar::IOManager* io_woker = sylar::IOManager::GetThis()
              ,sylar::IOManager* accept_worker = sylar::IOManager::GetThis());
    // 关闭所有sock
    virtual ~TcpServer();
    // 可以bind ipv4, ipv6或者多个地址
    virtual bool bind(sylar::Address::ptr addr);
    // 会返回绑定失败的地址
    virtual bool bind(const std::vector<Address::ptr>& addr,
                        std::vector<Address::ptr>& fails);

    virtual bool start();
    virtual void stop();

    uint64_t getRecvimeout() const { return m_recvTimeout; }
    void setRecveout(uint64_t v) { m_recvTimeout = v; }

    std::string getName() const { return m_name; }
    virtual void setName(const std::string& v) { m_name = v;}

    virtual std::string toString(const std::string& prefix = "");

    bool isStop() const { return m_isStop; }

protected:
    // 每accept一个sock执行一次，sock的回调
    virtual void handleClient(Socket::ptr client);
    virtual void startAccept(Socket::ptr sock);

private:
    // listener sock数组
    std::vector<Socket::ptr> m_socks;
    IOManager* m_worker;
    // 工作调度器
    IOManager* m_ioWorker;

    // 服务器接受连接调度器
    IOManager* m_acceptWorker;
    // 接收超时事件
    uint64_t m_recvTimeout;
    // 服务器名称
    std::string m_name;

    bool m_isStop;

};

}




#endif